package com.cbd.controller;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cbd.pojo.Cbdpact;
import com.cbd.pojo.Company;
import com.cbd.pojo.Companycarport;
import com.cbd.pojo.Companypact;
import com.cbd.pojo.Level;
import com.cbd.pojo.Landlady;
import com.cbd.pojo.Operator;
import com.cbd.pojo.PageBean;
import com.cbd.pojo.User;
import com.cbd.pojo.PageBean;
import com.cbd.pojo.Personalcarport;
import com.cbd.service.LandladyService;
import com.cbd.service.OperatorService;
import com.cbd.util.IQuantity;

@Controller
public class OperatorController {
	@Resource(name = "operatorServiceImpl")
	private OperatorService operatorService;
	@Resource(name="landladyServiceImpl")
	private LandladyService ladyService;
	@RequestMapping("cbd/Operator/addCbdpact")
	public void addCbdpact(Cbdpact cbdpact) {
		operatorService.addCbdpact(cbdpact);
	}

	public void setOperatorService(OperatorService operatorService) {
		this.operatorService = operatorService;
	}

	public void setLadyService(LandladyService ladyService) {
		this.ladyService = ladyService;
	}

	@RequestMapping(path = "cbd/Operator/addCompanyCarprot")
	public void addCompanyCarprot(Companycarport carPort, PrintWriter pw) {
		try {
			operatorService.addCompanyCarport(carPort);
			pw.print("success");
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * <p>
	 * 创建时间: 2016年11月1日 下午9:17:00.
	 * </p>
	 * <p>
	 * 标题: initPactNo.
	 * </p>
	 * <p>
	 * 说明:初始化合约合同编号.
	 * </p>
	 * 
	 * @param @param
	 *            param 租户合同或者公司合约合同
	 * @param @param
	 *            pw
	 * @return void
	 * @throws @author
	 *             杨文晶<br>
	 * @version 1.0.0.0
	 */
	@RequestMapping(path = "cbd/Operator/initPactNo")
	public void initPactNo(String param, PrintWriter pw) {
		String pactNo = param + "" + new Date().getTime();
		try {
			pw.print(pactNo);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@RequestMapping(path = "cbd/Operator/addPact")
	public String addPact(@RequestParam(value = "Pic", required = false) CommonsMultipartFile file, Cbdpact cbdPact,
			HttpServletRequest req, PrintWriter pw) {
		String fileName = "";
		if (!file.isEmpty()) {
			fileName = changeFileName(file.getOriginalFilename());
		}
		String path = req.getSession().getServletContext().getRealPath("upload");
		try {
			file.getFileItem().write(new File("F:\\cbd\\cbdproject\\WebContent\\upload" + File.separator + fileName));
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		cbdPact.setPactPic("upload" + File.separator + fileName);
		operatorService.addCbdpact(cbdPact);
		int id = operatorService.findCbdPactIDByNo(cbdPact.getPactNO());
		cbdPact.setPactID(id);
		String cartPortID = req.getParameter("carportID");
		if (cartPortID != null && !"".equals(cartPortID)) {
			String carPortIDarray[] = cartPortID.split(",");
			List<Companycarport> carportList = new ArrayList<Companycarport>();
			if (carPortIDarray != null) {
				for (int i = 0; i < carPortIDarray.length; i++) {
					Companycarport carport = new Companycarport();
					carport.setCarportID(Integer.parseInt(carPortIDarray[i]));
					carport.setType(false);
					carport.setCbdpact(cbdPact);
					carportList.add(carport);
				}
			}
			operatorService.updateCbdCompanyCarport(carportList);
			return "redirect:welcome.jsp";
		} else {

			String[] cartPortNo = req.getParameterValues("carportNO");
			String[] address = req.getParameterValues("carportAddress");

			try {

				// file.getFileItem().write(new File(path + File.separator +
				// fileName));

				// carPort.setCbdpact(cbdPact);
				List<Companycarport> carportList = new ArrayList<Companycarport>();
				if (cartPortNo != null) {
					for (int i = 0; i < cartPortNo.length; i++) {
						Companycarport carport = new Companycarport();
						carport.setCarportNO(cartPortNo[i]);
						carport.setCarportAddress(address[i]);
						carport.setType(false);
						carport.setCbdpact(cbdPact);
						carportList.add(carport);
					}
				}
				operatorService.addCompanyCarport(carportList);
				return "redirect:welcome.jsp";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "error";
			}
			
		}

	}

	@RequestMapping(path = "cbd/Operator/addCompanyPact")
	public String addCompanyPact(Companypact companyPact, HttpServletRequest req, PrintWriter pw) {
		// 租户续约，用于保存原合同车位
		String cartPortID = req.getParameter("carportID");
		// 租户签约，用于给合同新添车位
		String[] cartPortNo = req.getParameterValues("carportNO");
		String[] address = req.getParameterValues("carportAddress");
		String[] protID = req.getParameterValues("carprotID");
		try {
			operatorService.addCompanyPact(companyPact);
			int id = operatorService.findCompanyPactIDByNo(companyPact.getPactNO());
			companyPact.setPactID(id);
			if (cartPortID != null && !"".equals(cartPortID)) {
				String carPortIDarray[] = cartPortID.split(",");
				List<Companycarport> carportList = new ArrayList<Companycarport>();
				if (carPortIDarray != null) {
					for (int i = 0; i < carPortIDarray.length; i++) {
						Companycarport carport = new Companycarport();
						carport.setCarportID(Integer.parseInt(carPortIDarray[i]));
						carport.setType(true);
						carport.setCompanyPact(companyPact);
						carportList.add(carport);
					}
				}
				operatorService.updateCompanyCarport(carportList);
				return "redirect:welcome.jsp";
			} else {
				List<Companycarport> carportList = new ArrayList<Companycarport>();
				if (cartPortNo != null) {
					for (int i = 0; i < cartPortNo.length; i++) {
						Companycarport carport = new Companycarport();
						carport.setCarportNO(cartPortNo[i]);
						carport.setCarportAddress(address[i]);
						carport.setType(true);
						carport.setCarportID(Integer.parseInt(protID[i]));
						carport.setCompanyPact(companyPact);
						carportList.add(carport);
					}
				}

				operatorService.updateCompanyCarport(carportList);
				return "redirect:welcome.jsp";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "error";
		}

	}

	@RequestMapping(path = "cbd/Operator/getCompany")
	public @ResponseBody List<Company> getCompany() {
		List<Company> list = operatorService.getAllCompany();
		// for(Company c:list){
		// c.setCbdpact(null);
		// c.setCompanypacct(null);
		// }
		return list;
	}

	@RequestMapping(path = "cbd/Operator/getCompanyByID")
	public @ResponseBody Company getCompanyByID(@RequestParam("id") String id) {

		return operatorService.getCompanyByID(Integer.parseInt(id));
	}

	/**
	 * <p>
	 * 创建时间: 2016年10月31日 上午9:41:06.
	 * </p>
	 * <p>
	 * 标题: changeFileName.
	 * </p>
	 * <p>
	 * 说明: 更改用户上传的图片名字，已防止图片名字重名的情况.
	 * </p>
	 * 
	 * @param @param
	 *            fileName 上传文件的名字
	 * @param @return
	 *            返回新的名字
	 * @return String
	 * @throws @author
	 *             杨文晶<br>
	 * @version 1.0.0.0
	 */
	public String changeFileName(String fileName) {
		long sys = System.currentTimeMillis();
		String newName = sys + "." + fileName.split("[.]")[1];
		return newName;
	}

	@RequestMapping(path = "cbd/Operator/findAllCompanyPactByPactNo", method = RequestMethod.POST)
	public @ResponseBody List<Companypact> findAllCompanyPactByPactNo(@RequestParam("cbdNo") String cbdNo) {
		List<Companypact> list = operatorService.findAllCompanyPactByPactNo(cbdNo.trim());
		for (Companypact c : list) {
			c.getComp().setCbdpact(null);
			c.getComp().setCompanypacct(null);
			for (Companycarport cc : c.getCompanycarport()) {
				cc.setCompanyPact(null);
			}
		}
		return list;
	}

	@RequestMapping(path = "cbd/Operator/findAllCbdPactByPactNo", method = RequestMethod.POST)
	public @ResponseBody List<Cbdpact> findAllCbdPactByPactNo(@RequestParam("cbdNo") String cbdNo) {
		List<Cbdpact> list = operatorService.findAllCbdPactByCbdNo(cbdNo.trim());
		for (Cbdpact c : list) {
			c.getCompany().setCbdpact(null);
			c.getCompany().setCompanypacct(null);
			for (Companycarport cc : c.getCompanycarport()) {
				cc.setCompanyPact(null);
			}

		}
		return list;
	}

	@RequestMapping(path = "cbd/Operator/findCompanyCarportByPactID", method = RequestMethod.POST)
	public void findCompanyCarportByPactID(@RequestParam("id") String id, PrintWriter pw) {
		if (id != null && !"".equals(id)) {
			List<Companycarport> clist = operatorService.findCompanyCarportByPactID(Integer.parseInt(id));
			if (clist.isEmpty()) {
				pw.print("success");
			} else {
				pw.print("error");
			}
		}

	}

	/**
	 * <p>
	 * 创建时间: 2016年11月1日 下午9:16:26.
	 * </p>
	 * <p>
	 * 标题: canclePactByID.
	 * </p>
	 * <p>
	 * 说明: 车位解约.
	 * </p>
	 * 
	 * @param @param
	 *            id
	 * @param @param
	 *            pw
	 * @return void
	 * @throws @author
	 *             杨文晶<br>
	 * @version 1.0.0.0
	 */
	@RequestMapping(path = "cbd/Operator/canclePact", method = RequestMethod.POST)
	public void canclePactByID(@RequestParam("id") String id, PrintWriter pw) {
		try {
			operatorService.canclePactByID(Integer.parseInt(id));
			pw.write("success");
		} catch (Exception e) {
			pw.write("error");
		}

	}

	@RequestMapping(path = "cbd/Operator/cancleCompPact", method = RequestMethod.POST)
	public void cancleCompPactByID(@RequestParam("id") String id, PrintWriter pw) {
		try {
			operatorService.cancleCompPactByID(Integer.parseInt(id));
			pw.write("success");
		} catch (Exception e) {
			pw.write("error");
		}

	}

	@RequestMapping(path = "cbd/Operator/findAllCarPort", method = RequestMethod.POST)
	public @ResponseBody List<Companycarport> findAllCarPort() {
		return operatorService.findAllCarPort();
	}

	@RequestMapping(path = "showPIM", method = RequestMethod.POST)
	public @ResponseBody List<Object[]> showPIM(@RequestParam("id") String id, HttpServletRequest req) {
		int id1 = Integer.parseInt(id);
		req.getSession().setAttribute("id", id1);
		// System.out.println( "id="+id);
		List<Object[]> list = operatorService.showPIM(id1);
		return list;
	}

	@RequestMapping(path = "updatePIM")
	public String updatePIM(HttpServletRequest req) {
		String tiao = "";
		String pwd = req.getParameter("password");
		String tel = req.getParameter("operatorTel");
		int id = (int) req.getSession().getAttribute("id");
		int cou = operatorService.updatePIM(pwd, tel, id);
		if (cou == 1) {
			tiao = "redirect:cbd/Operator/operator.jsp";
		} else {
			tiao = "redirect:cbd/Operator/PIM.jsp";
		}
		return tiao;
	}

	@RequestMapping("cbd/Operator/countLandladyPageCount")
	public @ResponseBody int countLandladyPageCount(HttpServletRequest request) {
//		int pageSize = IQuantity.pageSize;
		int pageSize = IQuantity.pageSize;
		// 查找所有未通过审核的包租婆
		List<Landlady> landladies = operatorService.findAllEnsureLandlady();
		int ladyLen = landladies.size();
		int pageCount = ladyLen % pageSize == 0 ? ladyLen / pageSize : ladyLen / pageSize + 1;
		return pageCount;
	}
	@RequestMapping("cbd/Operator/findOnePageLandlady")
	public @ResponseBody List<Object[]> findOnePageLandlady(HttpServletRequest request){
		int pageSize = IQuantity.pageSize;
		int currentPage = Integer.parseInt(request.getParameter("currentPage"));
		return operatorService.findOnePageEnsureLandlady(pageSize, currentPage);
	}
	@RequestMapping("cbd/Operator/findLandladyByLadyID")
	public @ResponseBody Landlady findLandladyByLadyID(HttpServletRequest request){
		int ladyID = Integer.parseInt(request.getParameter("landladyID"));
		return operatorService.findLandladyByLadyID(ladyID);
	}
	@RequestMapping("cbd/Operator/passLandladyRequest")
	public void passLandladyRequest(HttpServletRequest request,PrintWriter writer){
		int ladyID = Integer.parseInt(request.getParameter("landladyID"));
		int result = operatorService.passLandladyRequest(ladyID);
		writer.print("");
	}
	/**
	 * <p>创建时间: 2016年11月3日 下午1:14:46.</p>
	 * <p>标题: findAllUnAbelPort.</p>
	 * <p>说明: 显示所有待审车位.</p>
	 * @param @return
	 * @return List<Personalcarport>
	 * @throws
	 * @author 杨文晶<br>
	 * @version 1.0.0.0
	 */
	@RequestMapping(path="cbd/Operator/findAllUnAbelPort")
	public @ResponseBody PageBean findAllUnAbelPort(@RequestParam("curpage")String curPage){
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(Integer.parseInt(curPage));
		pageBean.setPageSize(IQuantity.pageSize);
		pageBean =operatorService.findAllUnAbelPort(pageBean);
		 List<Landlady> list = (List<Landlady>) pageBean.getList();
		for(Landlady l :list){
			for(Personalcarport p:l.getPersonalcarport()){
				p.setLandlady(null);
			}
		}
		return pageBean;
	}
	/**
	 * <p>创建时间: 2016年11月4日 上午10:52:59.</p>
	 * <p>标题: findAllUnablePortByLadyID.</p>
	 * <p>说明: 通过包租婆ID 查找该用户下面的所有车位.</p>
	 * @param @param landyID
	 * @param @return
	 * @return List<Landlady>
	 * @throws
	 * @author 杨文晶<br>
	 * @version 1.0.0.0
	 */
	@RequestMapping(path="findAllUnablePortByLadyID")
	public @ResponseBody List<Landlady> findAllUnablePortByLadyID(@RequestParam("landyID") String landyID){
		
		List<Landlady> list =operatorService.findAllUnablePortByLadyID(Integer.parseInt(landyID));
		for(Landlady l :list){
			for(Personalcarport p:l.getPersonalcarport()){
				p.setLandlady(null);
			}
		}
		return list;
	}
	@RequestMapping(path="findUnableProtByLadyID")
	public @ResponseBody PageBean findAllUnableProtByLadyID(@RequestParam("landyID") String landyID,@RequestParam("curPage") String curPage){
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(Integer.parseInt(curPage));
		pageBean.setPageSize(IQuantity.pageSize);
		pageBean = operatorService.findUnableProtByLadyID(pageBean,Integer.parseInt(landyID));
		List<Personalcarport> list = (List<Personalcarport>) pageBean.getList();
		for(Personalcarport p : list){
			p.getLandlady().setPersonalcarport(null);
		}
		return pageBean;
	}
	@RequestMapping(path="accept")
	public void accept(@RequestParam("id")String id,PrintWriter pw){
		try {
			operatorService.accept(Integer.parseInt(id));
			pw.print("success");
		} catch (Exception e) {
			// TODO: handle exception
			pw.println("error");
		}
		
	}
	@RequestMapping(path="cbd/Operator/findAllOperator",method=RequestMethod.POST)
	public @ResponseBody PageBean findAllOperator(String curPage){
		
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(Integer.parseInt(curPage));
		pageBean = operatorService.findAllOperator(pageBean);
		System.out.println(pageBean.getList().size()+" "+pageBean.getCountPage()+" "+pageBean.getCurPage()+" "+pageBean.getId()+" "+pageBean.getPageSize()+" "+pageBean.getList().size());
		
		return pageBean;
	}
	@RequestMapping(path="cbd/Operator/addOperator",method=RequestMethod.POST)
	public String addOperator(@RequestParam("levels")String[] levels,@RequestParam("userName")String userName,@RequestParam("userPWD")String userPWD,@RequestParam("operatorName")String operatorName,@RequestParam("operatorTel")String operatorTel){
		Operator operator = new Operator();
		operator.setOperatorName(operatorName);
		operator.setOperatorTel(operatorTel);
		User user = new User();
		user.setUserRole(3);
		operator.setUser(user);
		operator.getUser().setUserName(userName);
		operator.getUser().setUserPWD(userPWD);
		List<Level> l = new ArrayList<Level>();	
		for (String level : levels) {
			Level le = new Level();
			le.setLevelID(1);
			switch(level){
				case "1":break;
				case "2":le.setLevelID(2);break;
				case "3":le.setLevelID(3);break;
				case "4":le.setLevelID(4);break;
			}
			l.add(le);
		}
		operator.setLevels(l);
		operatorService.addOperator(operator);
		return "cbd/Operator/operator";
	}
	@RequestMapping(path="cbd/Operator/findOperatorbyUserId",method=RequestMethod.POST)
	public @ResponseBody Operator findOperatorBuUserId(String id){
		return operatorService.findOperatorBuUserId(Integer.parseInt(id));				
	}
	
	@RequestMapping(path="cbd/Operator/updateOperatorbyUserId",method=RequestMethod.POST)
	public String updateOperatorbyUserId(@RequestParam("id") String id,@RequestParam("levels") String[] level){
		List<Integer> list = new ArrayList<Integer>();
		for (String string : level) {
			list.add(Integer.parseInt(string));
		}
		operatorService.updateLevelByOperatorId(list, Integer.parseInt(id));
		return "/cbd/Operator/operator";
	}

	@RequestMapping(path="cbd/Operator/delOperatorById",method=RequestMethod.POST)
	public void delOperatorById(@RequestParam("id") String id,PrintWriter pw){
		try {
			operatorService.deleteOperator(Integer.parseInt(id));
			pw.write("success");
		} catch (Exception e) {
			pw.write("error");
		}
	}
	@RequestMapping(path="cbd/Operator/findLevel",method=RequestMethod.POST)
	public @ResponseBody List<Integer> findLevel(@RequestParam("id") String id){
		List<Integer> l1 = new ArrayList<Integer>();
		List<Integer> l2 = new ArrayList<Integer>();
		try {
			List<Level> levels = findOperatorBuUserId(id).getLevels();			
			l1.add(1);
			l1.add(2);
			l1.add(3);
			l1.add(4);			
			for (Level level : levels) {
				l2.add(level.getLevelID());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		l1.removeAll(l2);
		return l1;
	}
	
	@RequestMapping("cbd/Operator/refuseLandladyRequest")
	public void refuseLandladyRequest(HttpServletRequest request,PrintWriter writer){
		int ladyID = Integer.parseInt(request.getParameter("landladyID"));
		ladyService.deleteLandladyAndUserByLadyID(ladyID);
		writer.print("");
	}
}
